<template>
  <div id="login">
    <div class="main">
      <div class="label">Login with your account</div>
      <input type="text" v-model="uid" class="input" placeholder="account" />
      <input type="password" v-model="psd" class="input" placeholder="password" />
      <div class="error" v-if="loginError">{{errorMsg}}</div>
      <input type="button" class="button" value="Login" @click="doLogin" />
      <router-link :to="{path:'/register'}" class="forget label">create an account</router-link>
      <div class="forget label">forget passsword?</div>
    </div>
  </div>
</template>
<script>
import { login } from "../../api/interface";
export default {
  data() {
    return {
      uid: "",
      psd: "",
      /**判断登录是否出错，为true表示登录错误，并显示相应的提示文字 */
      loginError: false,
      /**错误的描述语句 */
      errorMsg: "",
    };
  },
  mounted(){
    let dom = document.getElementById("login");
    if(this.isMobile()){
      dom.classList.add("mobile-background");
    }else{
      dom.classList.add("pc-background");
    }
  },
  methods: {
    /**
     * 点击登录按钮
     */
    doLogin() {
      if (this.uid == "" || this.psd == "") {
        this.loginError = true;
        this.errorMsg = "account or password is empty!";
        return;
      }
      login(this.uid,this.psd).then(res=>{
        let data = res.data;
        //如果code为200则表示登录成功
        if(data.code == 200){
          this.loginError = false;
          this.$store.dispatch('changeToken', data.data.token);
          this.$store.dispatch('changeUserName', data.data.username);
          this.$router.push({path:'/main',query:{login:true}});
        }else{
          this.loginError = true;
          this.errorMsg = "account or passsword is error";
        }
      }).catch(error=>{
        alert("服务器错误！");
      })
    },
  },
};
</script>
<style lang="less" scoped>
#login {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.main {
  width: 17rem;
  height: 18rem;
  background-color: #e5d8e1;
  opacity: 0.8;
  border-radius: 6px;
  box-shadow: 2px 2px 2px gray;
  display: flex;
  flex-direction: column;
  align-items: center;
  .label {
    width: 80%;
    color: #585858;
    margin-top: 2rem;
    font-size: 0.8rem;
  }
  .input,
  .button {
    width: 80%;
    height: 1.9rem;
    border-radius: 5px;
    margin-top: 1.1rem;
  }
  input::placeholder {
    font-size: 0.8rem;
  }
  .button {
    background-color: #0396db;
    color: white;
    cursor: pointer;
    position: relative;
  }
  .button:hover {
    top: 1px;
    left: 1px;
  }
  .error {
    width: 80%;
    color: red;
    font-size: 0.8rem;
  }
  .forget {
    cursor: pointer;
    text-align: center;
    margin-top: 0.7rem;
  }
  .forget:hover {
    color: midnightblue;
  }
}
</style>